package com.admin.infrastructure;

import com.admin.domain.modle.Play;
import com.admin.utils.HaiyinException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * description 海印统一接口工具类. Created with IntelliJ IDEA. User: WeiDa Date:
 * 2017-4-17 Time: 20:04
 */
public final class RemoteDataUtil {

    private static final String KEY = "5a37fb52-263c-437d-ad7e-cdc139f4a21b";
    private static final String ORDER_KEY = "524f91b3-08f6-463b-a4a9-13b2e2912478";
    private static final String PLAY_URL = "http://ticket.000861.com/ticket/playinformation";
    private static final String SEAT_URL = "http://ticket.000861.com//ticket/SeatInformation";
    private static final String ORDER_URL = "http://ticket.000861.com/ticket/ordercheck";
    private static final Charset UTF8 = Charset.forName("UTF-8");
    /**
     * 访问超时时间
     */
    private static final int READ_TIMEOUT = 180;

    private static final Logger LOGGER = LoggerFactory.getLogger(RemoteDataUtil.class);

    /**
     * description 演出列表 User: WeiDa Date: 2017-4-21 Time: 0:15
     */
    public static List<Play> postHaiyinShowList() {
        OkHttpClient client = new OkHttpClient().newBuilder().readTimeout(READ_TIMEOUT, TimeUnit.SECONDS).build();
        HttpUrl getUrl = HttpUrl.parse(PLAY_URL).newBuilder().build();
        LOGGER.debug("调用海印接口");
        RequestBody postBody = new FormBody.Builder().add("key", KEY).add("method", "getPlayList").build();
        Request request = new Request.Builder().post(postBody).url(getUrl).build();
        Response response = null;
        try {
            response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                JSONObject playObj = JSON.parseObject(response.body().byteStream(), UTF8, JSONObject.class);
                LOGGER.debug("调用海印接口输出：" + playObj);
                JSONArray objs = playObj.getJSONArray("playList");
                List<Play> plays = new ArrayList<Play>(objs.size());
                for (int i = 0; i < objs.size(); i++) {
                    plays.add(postHaiyinPlayDetail(objs.getJSONObject(i).getIntValue("id")));
                }
                return plays;
            }
        } catch (IOException e) {
            LOGGER.error("海印接口请求失败", e);
        } finally {
            if (response != null) {
                try {
                    response.body().close();
                } catch (final Throwable th) {
                    System.out.println(th.getMessage());
                }
            }
        }
        throw new HaiyinException("haiyin request fail...");
    }

    /**
     * description 演出详情
     * http://ticket.000861.com/ticket/playinformation?key=5a37fb52
     * -263c-437d-ad7e-cdc139f4a21b&method=getPlayDetail&id=1
     * {"hour":13,"playDate" :"2016-02-08
     * 00:00:00","minPrice":60,"name":"5555","id" :1,"maxPrice":4880,
     * "saleDate":["2017-04-20","2017-04-21","2017-04-22","2017-04-23"
     * ,"2017-04-24","2017-04-25"],"minute":21,"status":"0204002"} User: WeiDa
     * Date: 2017-4-20 Time: 23:17
     */
    public static Play postHaiyinPlayDetail(int id) {
        OkHttpClient client = new OkHttpClient().newBuilder().readTimeout(READ_TIMEOUT, TimeUnit.SECONDS).build();
        HttpUrl getUrl = HttpUrl.parse(PLAY_URL).newBuilder().build();
        LOGGER.debug("调用海印详情接口");
        RequestBody postBody = new FormBody.Builder().add("key", KEY).add("method", "getPlayDetail")
                .add("id", String.valueOf(id)).build();
        Request request = new Request.Builder().post(postBody).url(getUrl).build();
        Response response = null;
        try {
            response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                String message = response.body().string();
                LOGGER.debug("调用海印详情接口输出：{}", message);
                return JSON.parseObject(message, Play.class);
            }
        } catch (IOException e) {
            LOGGER.error("海印详情接口请求失败", e);
        } finally {
            if (response != null) {
                try {
                    response.body().close();
                } catch (final Throwable th) {
                    System.out.println(th.getMessage());
                }
            }
        }
        throw new HaiyinException("haiyin request fail...");
    }

    /**
     * description 演出座位信息 User: WeiDa Date: 2017-4-20 Time: 23:58
     */
    public static String postHaiyinSeatList(String palyDate, String playId) {
        OkHttpClient client = new OkHttpClient().newBuilder().readTimeout(READ_TIMEOUT, TimeUnit.SECONDS).build();
        HttpUrl getUrl = HttpUrl.parse(SEAT_URL).newBuilder().build();
        LOGGER.debug("调用海印seat接口");
        RequestBody postBody = new FormBody.Builder().add("key", KEY).add("playDate", palyDate).add("playId", playId)
                .build();
        Request request = new Request.Builder().post(postBody).url(getUrl).build();
        Response response = null;
        try {
            response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                String message = response.body().string();
                LOGGER.debug("调用海印seat接口输出：" + message);
                return message;
            }
        } catch (IOException e) {
            LOGGER.error("海印seat接口请求失败", e);
        } finally {
            if (response != null) {
                try {
                    response.body().close();
                } catch (final Throwable th) {
                    System.out.println(th.getMessage());
                }
            }
        }
        throw new HaiyinException("haiyin request fail...");
    }

    /**
     * description 订单提交到单机 返回-1 错误 否则返回订单ID User: WeiDa Date: 2017-4-21 Time:
     * 0:16 "playId": 10, “remoreId”: “XXXXXXXX” "phoneNumber": "18816793325",
     * "method": "check", "orderId": "", "playDate": "2017-04-06 00:00:00",
     * "name": "xxxx", "ids": vids, 座位集合 1,2
     */
    public static JSONObject postHaiyinOrder(JSONObject parameter) {
        OkHttpClient client = new OkHttpClient().newBuilder().readTimeout(READ_TIMEOUT, TimeUnit.SECONDS).build();
        HttpUrl getUrl = HttpUrl.parse(ORDER_URL).newBuilder().build();
        LOGGER.debug("调用海印order接口");
        parameter.put("key", ORDER_KEY);
        RequestBody postBody = new FormBody.Builder().add("parameter", parameter.toJSONString()).build();
        Request request = new Request.Builder().post(postBody).url(getUrl).build();
        Response response = null;
        try {
            response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                String message = response.body().string();

                LOGGER.warn("====" + message);
                JSONObject obj = JSON.parseObject(message);
                LOGGER.debug("调用海印order接口输出{}：{}",parameter.toJSONString(), obj);
                return obj;
            }
        } catch (IOException e) {
            LOGGER.error("海印order接口请求失败", e);
        } finally {
            if (response != null) {
                try {
                    response.body().close();
                } catch (final Throwable th) {
                    System.out.println(th.getMessage());
                }
            }
        }
        throw new HaiyinException("haiyin request fail...");
    }

    public static int postHaiyinOrderCheck(String remoteId, int playId, String playDate, int... seats) {
        JSONObject parameter = new JSONObject();
        parameter.put("method", "check");
        parameter.put("playId", playId);
        parameter.put("playDate", playDate);
        parameter.put("remoteId", remoteId);
        parameter.put("ids", StringUtils.join(seats, ','));
        JSONObject obj = postHaiyinOrder(parameter);
        String orderId = obj.getString("orderId");
        if (orderId.equalsIgnoreCase("false")) {
            throw new RuntimeException("order fail...");
        }
        return Integer.parseInt(orderId);
    }

    /**
     * description 订单支付确认 User: WeiDa Date: 2017-4-21 Time: 13:12 parameter 包含
     * method key orderId
     */
    public static boolean postHaiyinOrderPay(int orderId,String name,String phoneNumber,String tradNo) {
        JSONObject parameter = new JSONObject();
        parameter.put("method", "pay");
        parameter.put("orderId", orderId);
        parameter.put("name", name);
        parameter.put("phoneNumber", phoneNumber);
        parameter.put("tradNo", tradNo);
        JSONObject obj = postHaiyinOrder(parameter);
        return obj != null && obj.getBooleanValue("payStatus");
    }

    /**
     * description 取消订单支付 User: WeiDa Date: 2017-4-21 Time: 13:19
     */
    public static boolean postHaiyinOrderCancel(int orderId) {
        JSONObject parameter = new JSONObject();
        parameter.put("method", "cancel");
        parameter.put("orderId", orderId);
        JSONObject obj = postHaiyinOrder(parameter);
        return obj != null && obj.getBooleanValue("cancelStatus");
    }

    public static boolean postHaiyinOrderIsWriteOff(int orderId) {
        JSONObject parameter = new JSONObject();
        parameter.put("method", "isWriteOff");
        parameter.put("orderId", orderId);
        JSONObject obj = postHaiyinOrder(parameter);
        return obj != null && obj.getBooleanValue("writeOffStatus");
    }

    public static JSONObject getWeixin(String authUrl){
        OkHttpClient client = new OkHttpClient().newBuilder()
                .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
                .build();

        HttpUrl getUrl = HttpUrl.parse(authUrl).newBuilder()
                .build();
        LOGGER.info("调用微信授权接口");
        Request request = new Request.Builder()
                .url(getUrl)
                .build();
        Response response;
        try {
            response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                String message = response.body().string();
                JSONObject obj = JSON.parseObject(message);
                return obj;

            }
        } catch (IOException e) {
            LOGGER.error("微信授权接口请求失败", e);
        }
        return null;
    }
    /**
     * description User: WeiDa Date: 2017-4-21
     * parameter={"playId":"10","phoneNumber"
     * :"18816793305","method":"check","orderId"
     * :"1422","playDate":"2017-03-28%2000:00:00"
     * ,"name":"吴文烁","ids":"3126,3128",
     * "key":"524f91b3-08f6-463b-a4a9-13b2e2912478",remoreId="4455"}
     * "ids":"3126,3128", Time: 10:55
     */
    public static void main(String[] args) {
        System.out.println("http://op45vuqf3.bkt.clouddn.com/5905641be4b0fa1f71972675".length());
        String date = "2017-04-29 00:00:00";
        System.out.println(date.substring(0,9));
        Map<String, String> map = new HashMap<>(10);
        map.put("method", "check");
        map.put("playDate", "2017-03-28 00:00:00");
        map.put("playId", "10");
        map.put("remoteId", "4455");
        map.put("phoneNumber", "18816793305");
        map.put("name", "zhangsan");
        map.put("ids", "3126,3128");
        map.put("orderId", "-1");
        map.put("key", ORDER_KEY);
        postHaiyinOrderCancel(6648);
        // postHaiyinOrder(JSON.toJSONString(map));
       // System.err.println(postHaiyinSeatList("2017-04-29 12:07:21", "1"));
        // postHaiyinPlayDetail("1");
        // System.err.print(postHaiyinShowList());
    }
}
